package com.whc.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whc.common.Cache;
import com.whc.entity.User;
import com.whc.mapper.UserMapper;
import com.whc.service.UserService;
import com.whc.util.AssertUtil;
import com.whc.util.PasswordUtil;
import com.whc.vo.TokenVO;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 *
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Override
    public TokenVO login(String username, String password) {
        User user = lambdaQuery()
                .eq(User::getUsername, username)
                .one();
        AssertUtil.isNull(user, "用户不存在");
        AssertUtil.isFalse(PasswordUtil.verify(password, user.getPassword(), user.getSalt()), "密码错误");
        String token = UUID.randomUUID().toString().replace("-", "");
        TokenVO tokenVO = new TokenVO(token, LocalDateTime.now());
        Cache.tokens.put(token, tokenVO);
        return tokenVO;
    }

    @Override
    public TokenVO refresh(String token) {
        TokenVO tokenVO = Cache.tokens.get(token);
        AssertUtil.isNull(tokenVO, "刷新失败");
        token = UUID.randomUUID().toString().replace("-", "");
        tokenVO = new TokenVO(token, LocalDateTime.now());
        Cache.tokens.put(token, tokenVO);
        return tokenVO;
    }
}



